﻿using System;
using System.Collections.Generic;
using AyuBookmark.Common.Input;
using AyuBookmark.Common.Interfaces;

namespace AyuBookmark.Service.Services
{
    /// <summary>
    /// 快捷键服务实现
    /// </summary>
    public class ShortcutService : IShortcutService
    {
        private readonly Dictionary<string, Action> _shortcuts = new Dictionary<string, Action>();
        private readonly HashSet<VirtualKeyCode> _pressedKeys = new HashSet<VirtualKeyCode>();

        /// <inheritdoc />
        public void ProcessKeyPress(VirtualKeyCode key)
        {
            // 记录按下的键
            _pressedKeys.Add(key);

            // 检查是否匹配任何快捷键
            foreach (var shortcut in _shortcuts)
            {
                var keys = ParseShortcutKey(shortcut.Key);
                if (IsKeysPressed(keys))
                {
                    shortcut.Value.Invoke();
                    break;
                }
            }
        }

        /// <inheritdoc />
        public void RegisterShortcut(VirtualKeyCode mainKey, params VirtualKeyCode[] modifierKeys)
        {
            var shortcutKey = BuildShortcutKey(mainKey, modifierKeys);
            if (!_shortcuts.ContainsKey(shortcutKey))
            {
                _shortcuts.Add(shortcutKey, () => { /* 默认空操作 */ });
            }
        }

        /// <inheritdoc />
        public void UnregisterShortcut(VirtualKeyCode mainKey, params VirtualKeyCode[] modifierKeys)
        {
            var shortcutKey = BuildShortcutKey(mainKey, modifierKeys);
            _shortcuts.Remove(shortcutKey);
        }

        /// <summary>
        /// 注册带操作的快捷键
        /// </summary>
        public void RegisterShortcut(Action action, VirtualKeyCode mainKey, params VirtualKeyCode[] modifierKeys)
        {
            var shortcutKey = BuildShortcutKey(mainKey, modifierKeys);
            _shortcuts[shortcutKey] = action;
        }

        #region 私有方法
        private string BuildShortcutKey(VirtualKeyCode mainKey, VirtualKeyCode[] modifierKeys)
        {
            var keys = new List<VirtualKeyCode>(modifierKeys) { mainKey };
            keys.Sort();
            return string.Join("+", keys);
        }

        private List<VirtualKeyCode> ParseShortcutKey(string shortcutKey)
        {
            var keys = new List<VirtualKeyCode>();
            foreach (var keyStr in shortcutKey.Split('+'))
            {
                if (Enum.TryParse(keyStr, out VirtualKeyCode key))
                {
                    keys.Add(key);
                }
            }
            return keys;
        }

        private bool IsKeysPressed(List<VirtualKeyCode> requiredKeys)
        {
            // 检查所有需要的键是否都按下了
            foreach (var key in requiredKeys)
            {
                if (!_pressedKeys.Contains(key))
                {
                    return false;
                }
            }
            return true;
        }
        #endregion
    }
}